//
//  PhotoBrowserViewCell.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/8/9.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SDWebImage
protocol PhotoBrowserCellDelegate: NSObjectProtocol {
   
    func photoBrowserCellZoom(scale: CGFloat)
    func photoBrowserCellEndZoom()

}
class PhotoBrowserViewCell: UICollectionViewCell {
    
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    var imageURL: NSURL? {
        didSet{
               indicator.startAnimating()
                self.imageView.image = nil
                resetScrollView()
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), dispatch_get_main_queue()) {
               self.imageView.sd_setImageWithURL(self.imageURL!, placeholderImage: nil) { (image , _ , _ , _ ) -> Void in
                
                self.indicator.stopAnimating()
                if image == nil {
                    print("加载图像失败")
                    return
                }
                self.setupImagePosition()
            }
           }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置图片尺寸比例
    private func displaySize(image:UIImage) -> CGSize {
        
        let scale = image.size.height / image.size.width
        let height = scale * scrollView.bounds.width
        
        return CGSize(width: scrollView.bounds.width, height: height)
    }	
    
    //设置图片位置，长短图的显示方式
    private func setupImagePosition() {
        let size = displaySize(imageView.image!)
        
        if size.height > scrollView.bounds.height {
            
            imageView.frame = CGRect(origin: CGPointZero, size: size)
        } else {
            let y = (scrollView.bounds.height - size.height) * 0.5
            
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0 , bottom: y, right: 0)
        }
        scrollView.contentSize = size
        
    }
    //设置界面
    private func setupUI() {
        
        contentView.addSubview(indicator)
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        let dict = ["sv":scrollView]
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        prepareScrollView()
    }
    private func prepareScrollView() {
        
          scrollView.delegate = self
          scrollView.maximumZoomScale = 2.0
          scrollView.minimumZoomScale = 0.5
    }
    
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    //MARK -懒加载
    private lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

extension PhotoBrowserViewCell: UIScrollViewDelegate {
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
        
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        photoDelegate?.photoBrowserCellZoom(imageView.transform.a)
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        if scale > 0.8 {
            var offSetX = (scrollView.bounds.width - view!.frame.width) * 0.5
            offSetX = offSetX < 0 ? 0 : offSetX
            
            var offSetY = (scrollView.bounds.height  - view!.frame.width) * 0.5
            
            offSetY = offSetY < 0 ? 0 : offSetY
            scrollView.contentInset = UIEdgeInsets(top: offSetX, left: offSetY, bottom: 0, right: 0)
        }
        
        photoDelegate?.photoBrowserCellEndZoom()
    }
}
